package com.hzcx.app.simplechat.ui.friend;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.google.gson.Gson;
import com.hyphenate.chat.EMMessage;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.ui.chat.event.ChatShareUserEvent;
import com.hzcx.app.simplechat.ui.friend.adapter.FriendAdapter;
import com.hzcx.app.simplechat.ui.friend.adapter.NewFriendAdapter;
import com.hzcx.app.simplechat.ui.friend.bean.FriendBean;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.friend.contract.FriendListByLableContract;
import com.hzcx.app.simplechat.ui.friend.event.FriendLablePeopleEvent;
import com.hzcx.app.simplechat.ui.friend.presenter.FriendListByLablePresenter;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.view.SideLetterBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 添加标签好友界面
 */
public class FriendListByLableActivity extends BaseActivity<FriendListByLablePresenter> implements SideLetterBar.OnLetterChangedListener,
        FriendListByLableContract.View {

    public static final String INTENT_LIST = "INTENT_LIST";
    public static final String INTENT_LIST_BUNDLE = "INTENT_LIST_BUNDLE";
    public static final String INTENT_MEMBER_IDS = "INTENT_MEMBER_IDS";

    @BindView(R.id.tv_title)
    public TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    public ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    public TextView tvTitleRight;
    @BindView(R.id.tv_next)
    public TextView tvNext;
    @BindView(R.id.swipe_target)
    public RecyclerView rvFriend;
    @BindView(R.id.side_bar)
    public SideLetterBar sideBar;
    @BindView(R.id.tv_overlay)
    public TextView tvOverlay;
    @BindView(R.id.swipeToLoadLayout)
    public SwipeToLoadLayout swipeToLoadLayout;
    public List<FriendBean> friendData;
    public NewFriendAdapter friendAdapter;

    public List<FriendBean> listData;
    public boolean haveMoreData = false; // 是否还有更多消息
    public int page = 1;
    public int pageSize  = 100;

    @Override
    public int getLayout() {
        return R.layout.activity_group_msg_friend_list;
    }

    @Override
    public void initPresenter() {
        mPresenter = new FriendListByLablePresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText("选择好友");
        tvTitleRight.setText("全选");

        friendData = new ArrayList<>();
        friendAdapter = new NewFriendAdapter(friendData, 1);
        rvFriend.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvFriend.setAdapter(friendAdapter);

        sideBar.setOverlay(tvOverlay);

        sideBar.setOnLetterChangedListener(this);

        friendAdapter.setOnFriendListItemOnClickListener((headerPos, contentPos, id, bean) -> {
            friendData.get(headerPos).getCity().get(contentPos).setChecked(!friendData.get(headerPos).getCity().get(contentPos).isChecked());
            friendAdapter.notifyDataSetChanged();
            setCheckedNum();
        });
        swipeToLoadLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
    }

    public void loadMore() {

    }

    @Override
    public void initData() {
        listData = new ArrayList<>();
        mPresenter.getFriendList(this);
        Object str = getIntent().getSerializableExtra(INTENT_LIST_BUNDLE);
        Object[] strList = (Object[]) str;
        if (null != strList) {
            for (int i = 0; i < strList.length; i++) {
                FriendBean bean = (FriendBean) strList[i];
                listData.add(bean);
            }
        }

        LogUtils.d(new Gson().toJson(listData));

    }

    @OnClick({R.id.tv_title_right, R.id.tv_next})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_title_right: // 全选
                if (friendData == null || friendData.size() <= 0) {
                    return;
                }
                for (int i = 0; i < friendData.size(); i++) {
                    if (friendData == null || friendData.get(i) == null || friendData.get(i).getCity() == null || friendData.get(i).getCity().size() <= 0) {
                        continue;
                    }
                    for (int j = 0; j < friendData.get(i).getCity().size(); j++) {
                        friendData.get(i).getCity().get(j).setChecked(true);
                    }
                }
                setCheckedNum();
                friendAdapter.notifyDataSetChanged();
                break;

            case R.id.tv_next:
                toNext();
                break;
        }
    }

    /**
     * 下一步
     */
     public void toNext() {
        if (setCheckedNum() <= 0) {
            showError("请选择好友");
            return;
        }
        List<FriendBean> beans = new ArrayList<>();
        for (int i = 0; i < friendData.size(); i++) {
            if (friendData == null || friendData.get(i) == null || friendData.get(i).getCity() == null || friendData.get(i).getCity().size() <= 0) {
                continue;
            }
            List<FriendCityBean> list = new ArrayList<>();
            for (int j = 0; j < friendData.get(i).getCity().size(); j++) {
                if (friendData.get(i).getCity().get(j).isChecked()) {
                    list.add(friendData.get(i).getCity().get(j));
                }
            }
            if (list != null && list.size() > 0) {
                FriendBean friendBean = new FriendBean();
                friendBean.setName(friendData.get(i).getName());
                friendBean.setCity(list);
                beans.add(friendBean);
            }
        }
        if (beans.size() <= 0) {
            showError("请选择好友");
            return;
        }

        finishAction(beans);
    }

    public void finishAction(List<FriendBean> beans) {
        EventBus.getDefault().post(new FriendLablePeopleEvent(beans));
        finish();
    }

    /**
     * 根据字母展示不同位置
     *
     * @param letter
     */
    @Override
    public void onLetterChanged(String letter) {
        if (letter.equals("↑")) {
            rvFriend.scrollToPosition(0);
            return;
        }
        for (int i = 0; i < friendData.size(); i++) {
            if (friendData.get(i) == null) {
                continue;
            }
            if (EmptyUtils.isEmpty(friendData.get(i).getName())) {
                continue;
            }
            if (letter.equals(friendData.get(i).getName())) {
                ((LinearLayoutManager) rvFriend.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                break;
            }
        }
    }

    /**
     * 好友列表获取成功
     *
     * @param data
     */
    @Override
    public void friendListResult(List<FriendBean> data) {
        try {
            friendData.clear();
            friendData.addAll(data);
            setDefaultCheckedData();
            friendAdapter.notifyDataSetChanged();

            // 改变右侧字母选项
            List<String> list=new ArrayList<>();
            list.add("↑");
            for (FriendBean bean:friendData){
                list.add(bean.getName());
            }
            String[] toBeStored = list.toArray(new String[list.size()]);
            sideBar.setContent(toBeStored);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 搜索好友返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void FriendSearchClcik(ChatShareUserEvent event) {
        if(event.getTag()==11) {
            for (int i = 0; i < friendData.size(); i++) {
                if (friendData == null || friendData.get(i) == null || friendData.get(i).getCity() == null || friendData.get(i).getCity().size() <= 0) {
                    continue;
                }
                for (int j = 0; j < friendData.get(i).getCity().size(); j++) {
                    if (friendData.get(i).getCity().get(j).getMember_id() == event.getBean().getMember_id()) {
                        friendData.get(i).getCity().get(j).setChecked(!friendData.get(i).getCity().get(j).isChecked());
                    }
                }
            }
            friendAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 添加头部
     */
    private ConstraintLayout consSearch;

    public void addGroupCreateHeader() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_home_header, null);
        consSearch = view.findViewById(R.id.cons_search);

        consSearch.setOnClickListener(view1 -> startActivity(new Intent(FriendListByLableActivity.this, FriendSearchActivity.class)
                .putExtra(FriendSearchActivity.INTENT_TAG, 11)));

        friendAdapter.addHeaderView(view);
    }

    public void goneCreateHeader(){
        if (consSearch!=null){
            consSearch.setVisibility(View.GONE);
        }
    }


    /**
     * 设置默认选中的好友
     */
    public void setDefaultCheckedData() {
        if (listData == null || listData.size() <= 0) {
            return;
        }
        for (FriendBean bean : listData) {
            if (bean == null || bean.getCity() == null || bean.getCity().size() <= 0) {
                continue;
            }
            for (FriendCityBean cityBean : bean.getCity()) {
                setCheckedData(cityBean.getMember_id());
            }
        }
    }

    private void setCheckedData(int id) {
        if (friendData == null || friendData.size() <= 0) {
            return;
        }
        for (FriendBean bean : friendData) {
            if (bean == null || bean.getCity() == null || bean.getCity().size() <= 0) {
                continue;
            }
            for (FriendCityBean cityBean : bean.getCity()) {
                if (cityBean.getMember_id() == id) {
                    cityBean.setChecked(true);
                }
            }
        }
        setCheckedNum();
    }

    /**
     * 获取选中总人数
     */
    public int setCheckedNum() {
        int num = 0;
        for (FriendBean bean : friendData) {
            if (friendData == null || bean == null || bean.getCity() == null || bean.getCity().size() <= 0) {
                continue;
            }
            for (FriendCityBean subBean : bean.getCity()) {
                if(subBean.isChecked()) {
                    num++;
                }
            }
        }
        if (num > 0) {
            tvNext.setText("完成(" + num + ")");
        } else {
            tvNext.setText("完成");
        }
        return num;
    }
}
